package uts

import (
	crand "crypto/rand"
	"fmt"
	"math/big"
	"math/rand"
	"strings"
)

var charArr = strings.Split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "")
var letterArr = strings.Split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "")

// RandInt 生成指定范围内的随机数
func RandInt(min, max int) int {
	if min == max {
		return min
	}
	if min > max {
		min, max = max, min
	}
	if i, err := crand.Int(crand.Reader, big.NewInt(int64(max-min))); err != nil {
		return rand.Intn(max-min) + min
	} else {
		return int(i.Int64()) + min
	}
}

// RandI64 生成指定范围内的随机数
func RandI64(min, max int64) int64 {
	if min == max {
		return min
	}
	if min > max {
		min, max = max, min
	}
	if i, err := crand.Int(crand.Reader, big.NewInt(max-min)); err != nil {
		return rand.Int63n(max-min) + min
	} else {
		return i.Int64() + min
	}
}

// RandNum 生成指定长度的数字字符串
func RandNum(n int) (num string) {
	for i := 0; i < n; i++ {
		num += Str(RandInt(0, 9))
	}
	return
}

// RandHex 生成指定长度的hex字符串
func RandHex(n int) (hexs string) {
	for i := 0; i < n; i++ {
		hexs += fmt.Sprintf(`%x`, RandInt(0, 16))
	}
	return
}

// RandChar 生成指定长度的大/小写字母和数字的字符串
func RandChar(n int) (chars string) {
	for i := 0; i < n; i++ {
		chars += ArrSampleOne(charArr)
	}
	return
}

// RandLetter 生成指定长度的大/小写字母的字符串
func RandLetter(n int) (chars string) {
	for i := 0; i < n; i++ {
		chars += ArrSampleOne(letterArr)
	}
	return
}

// RandIMEI 生成随机的手机IMEI串号
func RandIMEI() (imei string) {

	var x []int
	a, b := 0, 0
	for i := 0; i < 14; i++ {
		m := RandInt(IIf(i%7 == 0, 1, 0), 9)
		x = append(x, m)

		if i%2 == 0 {
			a += m
		} else {
			n := m * 2
			b += n/10 + n%10
		}
	}

	r := (a + b) % 10
	if r != 0 {
		r = 10 - r
	}

	return Join(x, "") + Str(r)
}
